import phaser from 'phaser';
import NetClient from '../types/NetClient';


/** 房间场景 */
export default class Room extends phaser.Scene {

    private roomId: number = 0;
    private clientNt: NetClient = null!;

    private teamNodeAraay: Element[] = [];
    private body: Element = null!;
    // private playerNodeAraay: Element[] = [];

    private playerList: any[] = [];

    constructor() {
        super('Room');
    }

    clearTeamPlayerListUi() {
        for (let i = 0; i < this.teamNodeAraay.length; i++) {
            this.teamNodeAraay[i].innerHTML = '';
        }
    }

    teamAddPlayer(teamNumber: number = 0, palyerInfo: any, headImg: string = 'assets/header/h1.jpg') {
        console.log('teamAddPlayer', teamNumber, palyerInfo);
        let item = document.createElement('div');
        item.setAttribute('id', 'playerRoomItem_' + palyerInfo.id);
        item.innerHTML = `
            <div class="roomPlayerItem" playerId="`+ palyerInfo.id + `">
                <img class="roomPlayerHeader" src="`+ headImg + `" />
                <div class="roomPlayerItemName">`+ palyerInfo.nickname + `</div>
                <span id="roomPlayerItemReady_`+ palyerInfo.id + `" class="iconfont roomPlayerItemReady">&#xe639</span>
            </div>`;

        if (palyerInfo.isReady == false) {
            let node = item.querySelector('#roomPlayerItemReady_' + palyerInfo.id);
            if (node) {
                node.innerHTML = '';
            }
        }
        this.teamNodeAraay[teamNumber].appendChild(item);
    }

    setRoomInfo(info: any) {
        let roomTitleUi = this.body.querySelector('#roomTitle');
        if (roomTitleUi) {
            roomTitleUi.innerHTML = `房间号：${info?.roomId}`;
        }
    }

    send(action: string, data: any = null) {
        if (this.clientNt.stateConnect == true) {
            this.clientNt.sendAction('Moba2D', action, data);
        }
    }

    roomInit(info: any = null) {
        if (info != null) {
            this.roomId = info?.roomId;
            this.setRoomInfo(info);

            this.clientNt = window.client;
            if (this.clientNt) {
                this.clientNt.currentObject = this;
            }
            this.send('getRoomPlayerList', { roomId: this.roomId });
        }

    }

    ready() {
        this.send('ready');
    }
    cancelReady() {
        this.send('cancelReady');
    }

    setPalyerReadyState(playerId: number, isReady: boolean = false) {
        for (let i = 0; i < this.playerList.length; i++) {
            if (this.playerList[i].id == playerId) {
                this.playerList[i].isReady = isReady;
                break;
            }
        }
        let node = this.body.querySelector('#roomPlayerItemReady_' + playerId);
        if (node) {
            if (isReady == true) {
                node.innerHTML = '&#xe639';
            } else {
                node.innerHTML = '';
            }
        }
    }

    playerDisconnect(playerId: number) {
        for (let i = 0; i < this.playerList.length; i++) {
            if (this.playerList[i].id == playerId) {
                this.playerList.splice(i, 1);
                break;
            }
        }
        let node = this.body.querySelector('#playerRoomItem_' + playerId);
        if (node) {
            node.remove();
        }
    }


    onNetworkRecv(status: boolean, action: string = '', data: any = null) {
        if (status == false) {
            console.log('网络异常');
            return;
        }
        if (action == 'getRoomPlayerList') {
            console.log(window.userInfo.playerInfo.id);
            this.clearTeamPlayerListUi();
            this.playerList = data;
            this.playerList.forEach(element => {
                // console.log(element);
                this.teamAddPlayer(element.team, element);
            });
        }
        if (action == 'newPlayerAddRoom') {
            this.send('getRoomPlayerList', { roomId: this.roomId });
        }
        if (action == 'ready') {
            console.log('准备成功');
            let playerId = data.playerId
            this.setPalyerReadyState(playerId, true);
        }
        if (action == 'cancelReady') {
            console.log('取消准备成功');
            let playerId = data.playerId
            this.setPalyerReadyState(playerId, false);
        }
        if (action == 'disconnected') {
            console.log('玩家已下线');
            // this.send('getRoomPlayerList', { roomId: this.roomId });
            console.log(data);
            this.playerDisconnect(data.player.id);
        }
        if (action == 'startGame') {
            console.log('开始游戏');
            this.scene.start('Preparation');
        }
    }



    create(info: any = null) {
        let gameWidth = <number>this.sys.game.config.width;
        let gameHeight = <number>this.sys.game.config.height;

        let bg = this.add.image(gameWidth / 2, gameHeight / 2, 'background');
        bg.scaleX = bg.scaleY = 0.5;
        bg.setSize(gameWidth, gameHeight);

        this.body = this.add.dom(gameWidth / 2, gameHeight / 2, 'div', 'background:rgba(0,0,0,0.3);  position: relative; width:' + gameWidth + 'px; height:' + gameHeight + 'px;').node;
        this.body.innerHTML = `
            <div id="roomTitle">房间号：1234567890</div>
            <div id="roomBox">
                <!--玩家列表1-->
                <div id="leftpalyerlist">
                </div>
                <div id="roommiddle">
                    <span class="iconfont" id="roomPklcon">&#xe642;</span>
                </div>
                <!--玩家列表2-->
                <div id="rightpalyerlist">
                </div>
            </div>
            <div id="readyButton" class="GameUIButton">准备</div>
        `;

        let leftNode = this.body.querySelector('#leftpalyerlist');
        if (leftNode) this.teamNodeAraay[0] = leftNode;

        let rightNode = this.body.querySelector('#rightpalyerlist');
        if (rightNode) this.teamNodeAraay[1] = rightNode;


        /** 处理准备按钮事件 */
        let readButton = this.body.querySelector('#readyButton');
        readButton?.addEventListener('click', () => {
            if (readButton.innerHTML == '准备') {
                readButton.innerHTML = '取消';
                // this.scene.start('Preparation');
                this.ready();

            } else if (readButton.innerHTML == '取消') {
                readButton.innerHTML = '准备'
                this.cancelReady();
            }
        });

        this.roomInit(info);
    }
}
